package com.poker.wiki.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.poker.common.utils.Result;
import com.poker.common.utils.SnowFlake;
import com.poker.wiki.Service.UserService;
import com.poker.wiki.entity.User;
import com.poker.wiki.req.UserLoginReq;
import com.poker.wiki.req.UserQueryReq;
import com.poker.wiki.req.UserSaveReq;
import com.poker.wiki.resp.UserLoginResp;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

@RestController
public class UserController {

    @Resource
    UserService userService;

    @Resource
    SnowFlake snowFlake;

    @Resource
    RedisTemplate redisTemplate;

    @RequestMapping("/getAllUser")
    public Result getAllUser(@Valid UserQueryReq req) {
        PageInfo<User> pageInfo = userService.getAllUser(req);
        return Result.success(pageInfo);
    }

    @PostMapping("/saveUser")
    public Result save(@RequestBody @Valid UserSaveReq req){

        // 密码加密
        req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));

        userService.save(req);
        return Result.success();
    }

    @DeleteMapping("/deleteUser/{id}")
    public Result delete(@PathVariable Long id){
        userService.delete(id);
        return Result.success();
    }

    @PostMapping("/login")
    public Result login(@RequestBody @Valid UserLoginReq req) {
        // 密码加密
        req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));

        UserLoginResp resp = userService.login(req);

        // 生成token
        Long token = snowFlake.nextId();
        resp.setToken(token.toString());

        // 保存到redis
        redisTemplate.opsForValue().set(token.toString(), JSONObject.toJSONString(resp), 3600*24, TimeUnit.SECONDS);

        return Result.success(resp);
    }

    @GetMapping("/logout/{token}")
    public Result logout(@PathVariable String token) {
        redisTemplate.delete(token);
        return Result.success();
    }

}
